using Common.Communal;
using ERP.Domain.Warehouse;
using MediatR;
using SqlSugar;
using Warehouse.API.Read.App.Commands;

namespace Warehouse.API.Read.App.Handers
{
    public class InventoryTransactionListHandler : IRequestHandler<InventoryTransactionList, ApiResult<ApiPaging<InventoryTransaction>>>
    {
        private readonly ISqlSugarClient SqlSugarClient;

        public InventoryTransactionListHandler(ISqlSugarClient sqlSugarClient)
        {
            SqlSugarClient = sqlSugarClient;
        }

        public Task<ApiResult<ApiPaging<InventoryTransaction>>> Handle(InventoryTransactionList request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<InventoryTransaction>> result = new ApiResult<ApiPaging<InventoryTransaction>>();
            result.Code = EnumCode.Ok;
            result.Message = "查询成功";

            int totalCount = 0;
            int totalPage = 0;

            // 必须提供产品名称，否则不返回数据
            if (string.IsNullOrWhiteSpace(request.ProductName))
            {
                ApiPaging<InventoryTransaction> emptyPage = new ApiPaging<InventoryTransaction>();
                emptyPage.TotalPage = 0;
                emptyPage.TotalCount = 0;
                emptyPage.Data = new List<InventoryTransaction>();
                result.Data = emptyPage;
                result.Message = "请提供产品名称进行查询";
                return Task.FromResult(result);
            }

            var query = SqlSugarClient.Queryable<InventoryTransaction>();

            if (!string.IsNullOrWhiteSpace(request.ProductName))
            {
                query = query.Where(x => x.ProductName.Contains(request.ProductName));
            }

            var list = query
                .OrderBy(x => x.Id, OrderByType.Desc)
                .ToPageList(request.pageindex, request.pagesize, ref totalCount, ref totalPage);

            ApiPaging<InventoryTransaction> page = new ApiPaging<InventoryTransaction>();
            page.TotalPage = totalPage;
            page.TotalCount = totalCount;
            page.Data = list;
            result.Data = page;

            return Task.FromResult(result);
        }
    }
}


